//
//  LoadSureVC.m
//  NtoccShipper
//
//  Created by mac on 2019/12/2.
//  Copyright © 2019 zhuchongjin. All rights reserved.
//

#import "LoadSureVC.h"
#import "HDPicModle.h"
#import "GetPhoto.h"
#import "LoadSureCell.h"
#import "OrderListDetailModel.h"
#import "XLImageViewer.h"

@interface LoadSureVC ()<UITableViewDelegate,UITableViewDataSource>{
    UIView* _imgParent;
    FlexFrameView *header;
//    int index;  // 记录图片的位置
//    int indeRelpace;
}
@property (nonatomic,strong) CJTableView *tableView;
//@property (nonatomic,strong) CJLabel *labloadSureImgIndex;
@property (nonatomic,strong) LoadSureCell *loadSureCell;
// 存储上传照片的数组  是否是修改照片
//@property (nonatomic,strong) NSMutableArray *arrMutaImgsUpLoad;
//@property (nonatomic,assign) BOOL isChangeImg; // 是否更改
//展示部分
@property (nonatomic,strong) NSMutableArray *arrTitles;
@property (nonatomic,strong) NSMutableArray *arrContent;
@property (nonatomic,strong) NSMutableArray *arrNetImgs;
@property (nonatomic,strong) OrderListDetailModel *model;
@end

@implementation LoadSureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitleName:CJLString(@"装货确认")];
    [self setBackLeftButton:@""];
    self.loadSureCell = [[LoadSureCell alloc]initWithFlex:nil reuseIdentifier:nil];

    [self.view addSubview:self.tableView];
//    [self createTableView];
    [self loadDetailData];
//    self.arrMutaImgsUpLoad = [[NSMutableArray alloc]init];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)loadDetailData{
    
//    [CJNetWork getSourcesOrderListDetailDataWithCode:self.strCode Success:^(id  _Nullable responseObject) {
//
//        self.model = (OrderListDetailModel *)responseObject;
//
//    }];
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderDetail/orderDetailInfoLoadAndUnloadConfirm",CJBaseUrl);
    NSDictionary *dicPar = @{@"code":self.strCode
                            };
    
    WS(ws);
    [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        
        [ws createTableViewWithDic:responseObject];
        
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];
}

/// 创建tableview 等
- (void)createTableViewWithDic:(NSDictionary *)dic{
    
       // coalUnit(货物单位 0：吨 1：立方米，2-件)   0 只有装车吨位   其他 有装车数量
//    OrderModel *orderModel = self.model.order;
//    orderModel.coalUnitName
    NSString *coalUnit = CJStringWithFormat(@"%@",dic[@"coalUnit"]);
    if (coalUnit.intValue == 0) {
        self.arrTitles = (NSMutableArray *)@[@"司机姓名",@"司机电话",@"货物名称",@"装车吨位（吨）",@"车牌号",@"装车时间"];
        self.arrContent = (NSMutableArray *)@[
            [CJRegular getIsStrEmpty:dic[@"driverName"]] ? @"":dic[@"driverName"],
            [CJRegular getIsStrEmpty:dic[@"driverPhone"]] ? @"":dic[@"driverPhone"],
            [CJRegular getIsStrEmpty:dic[@"coalTypeName"]] ? @"":dic[@"coalTypeName"],
            CJStringWithFormat(@"%@",@([[CJControl getThreeUnaryValueStr:dic[@"loadWeight"]] floatValue]).cj_description ),
            [CJRegular getIsStrEmpty:dic[@"vehicleLicense"]] ? @"":dic[@"vehicleLicense"],
            [CJRegular getIsStrEmpty:dic[@"fillTime"]] ? @"":dic[@"fillTime"]];
    }else{
        
        self.arrTitles = (NSMutableArray *)@[@"司机姓名",@"司机电话",@"货物名称",@"装车吨位（吨）",CJStringWithFormat(@"装车数量（%@）",[CJRegular getIsStrEmpty:dic[@"coalUnitName"]] ? @"":dic[@"coalUnitName"]),@"车牌号",@"装车时间"];
        self.arrContent = (NSMutableArray *)@[
            [CJRegular getIsStrEmpty:dic[@"driverName"]] ? @"":dic[@"driverName"],
            [CJRegular getIsStrEmpty:dic[@"driverPhone"]] ? @"":dic[@"driverPhone"],
            [CJRegular getIsStrEmpty:dic[@"coalTypeName"]] ? @"":dic[@"coalTypeName"],
            @([[CJControl getThreeUnaryValueStr:dic[@"loadWeight"]] floatValue]).cj_description,
            @([[CJControl getThreeUnaryValueStr:dic[@"loadQuantity"]] floatValue]).cj_description,
            [CJRegular getIsStrEmpty:dic[@"vehicleLicense"]] ? @"":dic[@"vehicleLicense"],
            [CJRegular getIsStrEmpty:dic[@"fillTime"]] ? @"":dic[@"fillTime"]];
    }
    
//    self.arrTitles = (NSMutableArray *)@[@"司机姓名",@"司机电话",@"货物名称",CJStringWithFormat(@"装车数量（%@）",dic[@"coalUnitName"]),@"车牌号",@"装车时间"];
//    self.arrContent = (NSMutableArray *)@[dic[@"driverName"],dic[@"driverPhone"],dic[@"coalTypeName"],CJStringWithFormat(@"%.2f",[dic[@"loadQuantity"] floatValue]),dic[@"vehicleLicense"],dic[@"fillTime"]];
    //    WS(ws);
    CGRect rcFrame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 0);
    header = [[FlexFrameView alloc] initWithFlex:@"LoadSureHeaderView" Frame:rcFrame Owner:self];
    header.flexibleHeight = YES;
    
    NSArray *listUrl = dic[@"loadImgUrlList"];
    [self.arrNetImgs removeAllObjects];
    
    NSMutableArray *list = [[NSMutableArray alloc]init];
    
    for (int i = 0; i < listUrl.count; i++) {
        
        if ([CJControl getIsEmpty:listUrl[i]]) {
            
        }else{
            [list addObject:listUrl[i]];
        }
    }
    
    
    if (list.count > 0) {
        
        for (int i = 0; i < list.count; i++) {
            [self.arrNetImgs addObject:list[i]];
            UIImageView* cell = [[UIImageView alloc]init];
            cell.userInteractionEnabled = YES;
            //        [cell enableFlexLayout:YES];
            UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickToSeeBigCell:)];
            cell.tag = i + 1000;
            [cell enableFlexLayout:YES];
            [cell addGestureRecognizer:tap];

            [cell setLayoutAttrStrings:@[
                         @"width",@"75",
                         @"height",@"75",
                         @"margin",@"1%",
                         @"alignItems",@"center",
                         @"justifyContent",@"center",
                         ]];
            [cell setViewAttr:@"bgColor" Value:@"#E4E9ED"];
            [cell setViewAttr:@"borderRadius" Value:@"0"];
            [_imgParent insertSubview:cell atIndex:i];
            [_imgParent markDirty];
            //    cell.layer.contents = (id) img.CGImage;
            //    UIImageView *imgV;
            [cell sd_setImageWithURL:[NSURL URLWithString:self.arrNetImgs[i]] placeholderImage:[UIImage imageNamed:@"zcj_error_image"]];

        }
    }
    
    [header layoutIfNeeded];
    self.tableView.tableFooterView= header;
    [self.tableView reloadData];
}

-(void)clickToSeeBigCell:(UIGestureRecognizer*)sender{
    UIView* cell = sender.view;
    [[XLImageViewer shareInstanse] showNetImages:self.arrNetImgs index:(int)cell.tag - 1000 fromImageContainer:cell];
}

- (void)btnSureLoadGoodsAction{
//    [CJAlert showStringDismissWithDelay:@"隐私协议"];
    WS(ws);
    CJAlertView *alert = [[CJAlertView alloc]initWithTitle:@"友情提示" strContent:@"请严格审核装车信息，确认无误后点击确认" ClickOnSure:^(NSString * _Nonnull strSure) {
        DLog(@"--------");
        [ws saveSureIsLoadingConfirm:@"1"];

    } ClickOnCancle:^(NSString * _Nonnull strCancle) {
        DLog(@"-=-=-=-=");
    }];
    
    alert.center=self.view.center;
    WLAlertView * alertView = [[WLAlertView alloc]init];
    alertView.containerView = alert;
    alertView.isTouchOtherUndissmiss=YES;
    [alertView show];
}

- (void)btnTurnDownLoadGoodsAction{
//    [CJAlert showStringDismissWithDelay:@"隐私协议"];
    WS(ws);
    CJAlertView *alert = [[CJAlertView alloc]initWithTitle:@"友情提示" strContent:[CJPromptInfo getHintPromptType:@"驳回" withNextStep:@"装车信息"] ClickOnSure:^(NSString * _Nonnull strSure) {
        [ws saveSureIsLoadingConfirm:@"2"];

    } ClickOnCancle:^(NSString * _Nonnull strCancle) {

    }];
    alert.center=self.view.center;
    WLAlertView * alertView = [[WLAlertView alloc]init];
    alertView.containerView = alert;
    alertView.isTouchOtherUndissmiss = YES;
    [alertView show];
}

/// 货主装货确认 0-否，1-是，2-驳回
/// @param strType <#strType description#>
- (void)saveSureIsLoadingConfirm:(NSString *)strType{
    
//    WS(ws);
//    CJAlertView *alert = [[CJAlertView alloc]initWithTitle:@"友情提示" strContent:[CJPromptInfo getHintPromptType:@"驳回" withNextStep:@"装车信息"] ClickOnSure:^(NSString * _Nonnull strSure) {
        [self btnSaveSureIsLoadingConfirm:strType];
//    } ClickOnCancle:^(NSString * _Nonnull strCancle) {
//
//    }];
//    alert.center=self.view.center;
//    WLAlertView * alertView = [[WLAlertView alloc]init];
//    alertView.containerView = alert;
//    alertView.isTouchOtherUndissmiss = YES;
//    [alertView show];
}

- (void)btnSaveSureIsLoadingConfirm:(NSString *)strType{
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tms-api/orderDetail/shipperConfirmLoading",CJBaseUrl);
    NSDictionary *dicPar = @{@"code":self.strCode,
                             @"isLoadingConfirm":strType,
    };
    
    WS(ws);
    [[HDNetworking sharedHDNetworking] PUT:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        
        if (ws.blockSuccess) {
            ws.blockSuccess(@"");
            [ws pop];
        }
        
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];
    
}

#pragma mark ----------table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.arrTitles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *identifier = @"LoadSureCell";
    LoadSureCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[LoadSureCell alloc] initWithFlex:nil reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    }
    [cell setCellInfoWithStr:self.arrTitles[indexPath.row] withContent:self.arrContent[indexPath.row]];
    return cell;
}

#pragma mark ----------lazy
- (NSMutableArray *)arrNetImgs{
    if (!_arrNetImgs) {
        _arrNetImgs = [[NSMutableArray alloc]init];
    }
    return _arrNetImgs;
}

- (NSMutableArray *)arrContent{
    if (!_arrContent) {
        _arrContent = [[NSMutableArray alloc]init];
    }
    return _arrContent;
}

- (NSMutableArray *)arrTitles{
    if (!_arrTitles) {
        _arrTitles = [[NSMutableArray alloc]init];
    }
    return _arrTitles;
}

- (CJTableView *)tableView{
    if (!_tableView) {
        _tableView = CJTableView.tbInitFrameStyle(CGRectMake(0, kTopHeight + CJTableToTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-kTopHeight - CJTableToTopHeight),UITableViewStylePlain)
        .tbDelegate(self)
        .tbDataSource(self)
        .tbSetOther(YES)
        .tbEstimatedRowHeight(YES)
//        .tbMjHeadFooter(YES)
        ;
//        WS(ws);
//        _tableView.blockMjHeader = ^(BOOL isheader) {
//
//            if (isheader) {
//                [ws downRefresh];
//            } else {
//                [ws upRefresh];
//            }
//
//        };

    }
    
    return _tableView;
}

//-(void)removeCell:(UIGestureRecognizer*)sender
//{
//    UIView* cell = sender.view;
//    [[XLImageViewer shareInstanse] showNetImages:self.arrMutaImgsUpLoad index:(int)cell.tag fromImageContainer:cell];
//}
//
//-(void)relpaceCell:(UIGestureRecognizer*)sender
//{
//    UIView* cell = [self.view viewWithTag:sender.view.tag - 100];
//      indeRelpace = (int)cell.tag;
//
//        self.isChangeImg = YES;
//        [GetPhoto getPhoto:self completion:^(UIImage *curImage, NSData *imageData) {
//
//            cell.layer.contents = (id) curImage.CGImage;
//
//            [self upLoadImageUImage:curImage withNSData:imageData];
//
//        }];
//        DLog(@"++++++ %ld",(long)cell.tag);
//}

////上传回单图片
//-(void)onAddImage
//{
//    DLog(@"++++++++++%d",index);
//
//    if (index >= 9) {
//        [CJAlert showStringDismissWithDelay:@"最多上传9张图片"];
//        return;
//    }
//
//    [GetPhoto getPhoto:self completion:^(UIImage *curImage, NSData *imageData) {
//
//
//        [self upLoadImageUImage:curImage withNSData:imageData];
////        [self.tableView reloadData];
//    }];
//
//}
//- (void)upLoadImageUImage:(UIImage *)img withNSData:(NSData *)imageData{
//
//    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/fileUpload",CJBaseUrl);
//
//    NSURL *str = [[NSURL alloc]initFileURLWithPath:[CJControl getImgFilePath:img]];
//
//    NSDictionary *dic = @{
//                          @"file":str
//                          };
//    HDPicModle *model = [[HDPicModle alloc]init];
//    model.pic = img;
//    model.picData = imageData;
//    model.picName = @"file";
//    model.fileName = [CJControl getImgFilePath:img];
//
//    WS(ws);
//    [[HDNetworking sharedHDNetworking] POST:strURL parameters:dic andPic:model progress:^(NSProgress * _Nullable progress) {
//        DLog(@"%lf", 1.0 * progress.completedUnitCount / progress.totalUnitCount);
//    } success:^(id  _Nonnull responseObject) {
//
//
//        DLog(@"+++++++%@",responseObject);
//
//        NSString *strStatus = CJStringWithFormat(@"%@",responseObject[@"status"]);
//
//        if (strStatus.integerValue == 0) {
//
//            if (ws.isChangeImg) {
//                [ws.arrMutaImgsUpLoad replaceObjectAtIndex:indeRelpace withObject:responseObject[@"data"]];
//            }else{
//
//                [ws.arrMutaImgsUpLoad addObject:responseObject[@"data"]];
//                UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(removeCell:)];
//
//                       DLog(@"怎加之后的++++++++++%d",index);
//
//                       UIView* cell = [[UIView alloc]init];
//                       cell.tag = index;
//                       [cell enableFlexLayout:YES];
//                       [cell addGestureRecognizer:tap];
//
//                       [cell setLayoutAttrStrings:@[
//                                                    @"width",@"75",
//                                                    @"height",@"75",
//                                                    @"margin",@"1%",
//                                                    @"alignItems",@"center",
//                                                    @"justifyContent",@"center",
//                                                    ]];
//                       [cell setViewAttr:@"bgColor" Value:@"#e5e5e5"];
//                       [cell setViewAttr:@"borderRadius" Value:@"10"];
//
//
//                       CJView *viewDelete = CJView.viewInit
//                       .viewFrame(CGRectMake(65, -2, 20, 20))
//                       .viewbgColor([UIColor cjClearColor])
//                       ;
//                       viewDelete.layer.contents = (id) [UIImage imageNamed:@"zcj_delete_img"].CGImage;
//                       [cell addSubview:viewDelete];
//
//                       UITapGestureRecognizer *tapRelpace=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(relpaceCell:)];
//                       viewDelete.tag = index + 100;
//                       [viewDelete addGestureRecognizer:tapRelpace];
//
//                       [_imgParent insertSubview:cell atIndex:index ];
//
//                       [_imgParent markDirty];
//                       [header layoutIfNeeded];
//                       self.tableView.tableHeaderView = header;
//
//                       cell.layer.contents = (id) img.CGImage;
//                       self.isChangeImg = NO;
//                       index++;
//                       self.labloadSureImgIndex.text = CJStringWithFormat(@"%d/9",index);
//            }
//        }
//
//        DLog("====== =%@",ws.arrMutaImgsUpLoad);
//
//    } failure:^(NSError * _Nonnull error) {
//        DLog(@"+++++++%@",error);
//
//    }];
//}

@end




